package com.cyandpos.pad.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.changyi.device.APApplication;
import com.cyandpos.pad.utils.log.LogUtils;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by Administrator on 2020/2/7.
 */

public class CommonUtils {

    /**
     * 字符串是否为空
     * @param str
     * @return true 如果str==null 或者 str.trim().equals("")
     */
    public static boolean isNullOrEmpty(String str) {
        return str == null || str.trim().equals("");
    }

    public static int isNullOrEmptyInt(String str) {
        int strInt = 0;
        if(str == null || str.trim().equals(""))
            strInt = 0;
        strInt = Integer.parseInt(str);
        return strInt;
    }

    /**
     * 自动补零
     * @param content 内容
     * @param length  指定长度
     * @return 前补零后的内容
     */
    public static String autoAddZero(String content, int length){
        if(isNullOrEmpty(content))
            return "";
        if(content.length()>=length){
            return content;
        }else{
            String newString = String.format("%0"+length+"d", Integer.parseInt(content));
            return newString;
        }

    }
    /**
     * 不足前面补零
     * @param source
     * @param length
     * @return
     */
    public static String addZero(int source,int length){

        if (source == 0 || length == 0)
            return "";
        String newString  = String.format("%0"+length+"d", source);

        return newString;
    }
    /**
     * 获得TextView 的内容
     *
     * @return
     */
    public static String getContent(TextView tv) {
        if (tv == null)
            return "";
        return tv.getText().toString().trim();
    }

    /**
     * 判断字符串ip是否是一个正确的IP地址
     *
     * @param ip
     * @return 如果参数ip是一个正确的IP则返回true, 否则返回false.
     */
    public static boolean isIp(String ip) {
        return Pattern.matches("^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$", ip);
    }

    /**
     * @param context
     * @return 返回本机的MAC地址ַ
     */
    public static String getMac(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifi.getConnectionInfo().getMacAddress();
    }

    /**
     * 返回本机的IP地址ַ
     */
    public static String getIp(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        int ipInt = info.getIpAddress();
        return (ipInt & 0xFF) + "." + ((ipInt >> 8) & 0xFF) + "." + ((ipInt >> 16) & 0xFF) + "." + (ipInt >> 24 & 0xFF);
    }

    /**
     * 判断WIFI是否可用
     */
    public static boolean isWifiEnable(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }

    /**
     * 获取当前版本号
     *
     * @param context
     * @return 当前版本号
     */
    public static int getCurrentVersionCode(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            System.out.println("获取当前版本的版本号出错：" + e);
            return 0;
        }
    }

    /**
     * 获取当前版本名称
     *
     * @param context
     * @return 当前版本号
     */
    public static String getCurrentVersionName(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            System.out.println("获取当前版本的版本名称出错：" + e);
            return "";
        }
    }

    /**
     * 判断SD卡是否插入
     *
     * @return 已经准备好则返回true, 否则返回false.
     */
    public static boolean isSdcardReady() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 网络类型
     */
    private String getNetType(Context context) {
        if (context == null) return "";
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo.State state = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            if (NetworkInfo.State.CONNECTED == state) return "WIFI";
            state = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
            if (NetworkInfo.State.CONNECTED == state) return "GPRS";
            return "NONE";
        }
        return "NONE";
    }

    /**
     * 根据context和layoutid渲染视图
     * @param context
     * @param layoutId
     * @return
     */
    public static View getViewById(Context context, int layoutId) {
        View view = View.inflate(context, layoutId, null);
        return view;
    }

    /**
     * 返回关于钱的中文式大写数字,仅支持到亿
     * @throws Exception
     * */
    public static String arabNumToChineseRMB(String moneyNum) throws Exception {
        String res="";
        int i=3;
        int len=moneyNum.length();
        if(len>12){
            throw new Exception("Number too large!");
        }
        if("0".equals(moneyNum))
            return "零元";
        //System.out.println(moneyNum);
        for(len--;len>=0;len--){
            res=PubData.ChineseUnit[i++]+res;
            int num=Integer.parseInt(moneyNum.charAt(len)+"");
            res=PubData.ChineseNum[num]+res;
        }
        return res.replaceAll("零[拾佰仟]", "零")
                .replaceAll("零+亿", "亿").replaceAll("零+万", "万")
                .replaceAll("零+元", "元").replaceAll("零+", "零");

    }

    /**
     * MD5加密(先加密后转换为大写)
     * @param string
     * @return
     */
    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString().toUpperCase();
    }

    /**
     * 字符串截取
     * @param content  要截取的字符串
     * @param start  开始位置
     * @param end    结束位置
     */
    public static String subString(String content,int start,int end){
        String str = "";
        if(isNullOrEmpty(content)){
            return str;
        }
        str = content.substring(start,end);
        return str;
    }

    //先转换为大写后加密
    public static String md5(String src){
        if (isNullOrEmpty(src)){
            return "";
        }else {
            String session ="";
            try{
                MessageDigest md5= MessageDigest.getInstance("md5");//返回实现指定摘要算法的 MessageDigest 对象。
                md5.update(src.getBytes());//先将字符串转换成byte数组，再用byte 数组更新摘要
                byte[] nStr = md5.digest();//哈希计算，即加密
                session = bytes2Hex(nStr);//加密的结果是byte数组，将byte数组转换成字符串
            }catch(Exception e){
                LogUtils.i("AAA","密码加密失败" +e.getMessage());
            }
            LogUtils.i("AAA","加密后的结果为：" +session);
            return session;
        }

    }

    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    /**
     * 根据context和layoutid渲染视图
     *
     * @param context
     * @param layoutId
     * @return
     */
    public static View getViewById(Context context, int layoutId, ViewGroup root,boolean attachToRoot) {
        View view = LayoutInflater.from(context).inflate(layoutId,root,attachToRoot);
        return view;
    }

    /**
     * 获取Json字符串
     * @param map
     * @return
     */
    public  static String  sortStrNewJsonStr(TreeMap<String, Object> map){
        Map<String, Object> newMap =new HashMap<String, Object>();
        TreeMap<String, Object> map2 = new TreeMap<String, Object>(new Comparator<String>() {
            public int compare(String obj1, String obj2) {
                // 升序排序
                return obj2.compareTo(obj1);
            }
        });
        map2 = map;
        Set<String> keySet = map2.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            LogUtils.d("sortStr方法中KEY的顺序为："+key);
            newMap.put(key,map2.get(key));
        }
        Gson gson = new Gson();
        String jsonStr = gson.toJson(newMap);
//        LocalLog.writeLog("sortStr整理的Params_json串为："+jsonStr);
        return jsonStr;
    }

    /**
     * 获取Map的toString内容
     * @param map
     * @return
     */
    public  static Map<String, Object> sortStrNewToString(TreeMap<String, Object> map){
        Map<String, Object> newMap =new HashMap<String, Object>();
        TreeMap<String, Object> map2 = new TreeMap<String, Object>(new Comparator<String>() {
            public int compare(String obj1, String obj2) {
                // 升序排序
                return obj2.compareTo(obj1);
            }
        });
        map2 = map;
        Set<String> keySet = map2.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
//            LocalLog.writeLog("sortStr方法中KEY的顺序为："+key);
            newMap.put(key,map2.get(key));
        }
        return newMap;
    }

    public static String getSystemModel() {
        return Build.MODEL;
    }

    /**
     * 不弹出输入法  但是有光标
     * @param et
     * @param act
     */
    public static void hideSoftInputButWithSelection(EditText et, Activity act) {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            et.setInputType(InputType.TYPE_NULL);
        } else {
            act.getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(et, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void setOnFocusStatus(final EditText et, String defaultValue) {
        Editable etext = et.getText();
        Selection.setSelection(etext, etext.length());
        et.setText(defaultValue);
        et.setFocusable(true);
        et.requestFocus();
    }

    public static void setOnFocusStatus2(final EditText et, String defaultValue) {
        et.setText(defaultValue);
        et.setSelection(defaultValue.length());
        et.setFocusable(true);
        et.requestFocus();
    }


    /**
     *
     * @param et 当前edittext
     * @param mContext 当前activity
     * @param isText 是否时文本
     */
    public static void setNoSoftware(EditText et,Activity mContext,boolean isText) {
        CommonUtils.hideSoftInputButWithSelection(et, mContext);
        if(true)
            et.setInputType(EditorInfo.TYPE_CLASS_TEXT);
//        else
//            et.setInputType(EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
        et.setImeOptions(EditorInfo.IME_ACTION_UNSPECIFIED);
    }

    public  static void insertEditTextContext(EditText et,String num){
        int index = et.getSelectionStart();
        Editable editable = et.getText();
        editable.insert(index, num);
    }

    public  static void clearInsertEditTextContext(EditText et,String num){
        et.setText(num);
        et.setSelection(et.getText().length());
    }

    public  static void delectEditTextContext(EditText et){
        if(et.getText().length()>0){
            int index = et.getSelectionStart();
            Editable editable = et.getText();
            if(index>=1)
            editable.delete(index-1, index);
        }
    }

    public static void getSystemPx(Context mContext){
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();

        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        LogUtils.i("TAG------screenWidth:",screenWidth+"");
        LogUtils.i("TAG------screenHeight:",screenHeight+"");
    }

    /**
     * 显示输入法
     *
     * @param et
     */
    public static void showSoftInput(EditText et) {
        InputMethodManager imm = (InputMethodManager) et.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 隐藏输入法
     *
     * @param et
     */
    public static void hideSoftInput(EditText et) {
        if (et == null) return;
        InputMethodManager imm = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = APApplication.mCotext.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    public static int getInt(String str) {
        if (TextUtils.isEmpty(str)){
            str = "0";
        }
        return Integer.parseInt(str);
    }
    /**
     * 字符串格式（补齐6位）
     * @param str
     * @param length
     * @return
     */
    public static String formatStr(String str, int length) {
        if (str == null) {
            return null;
        }
        int strLen = str.length();
        if (strLen == length) {
            return str;
        } else if (strLen < length) {
            int temp = length - strLen;
            String tem = "0";
            for (int i = 0; i < temp; i++) {
                str = tem + str;
            }
            return str;
        } else {
            return str.substring(0, length);
        }
    }

    /**
     * 金额验证
     * @param str
     * @return
     */
    public static boolean isNumber(String str){
        Pattern pattern=Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        Matcher match=pattern.matcher(str);
        return match.matches() != false;
    }
    public  static String handleStringNull(String s){
        if(s == null)
            return "";
        else
            return  s;
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        try {
            context.getPackageManager().getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static boolean isMobileNO(String mobiles) {
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个
        //"\\d{9}"代表后面是可以是0～9的数字，有9位
        String telRegex = "[1][34578]\\d{9}";
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }
}
